import os
from wsgiref.simple_server import make_server

"""
REQUEST_METHOD
QUERY_STRING
CONTENT_TYPE
"""


def app(env, make_resopnse):
    #     核心业务函数

    path = env.get('PATH_INFO')  # 请求资源路径

    headers = []  # 请求头信息
    body = []

    # 静态资源目录
    static_dir = 'static'
    if path == '/favicon.ico':
        res_path = os.path.join(static_dir, 'gitimg.jpg')
        headers.append(('content-type', 'image/jpeg'))
    elif path == '/':
        res_path = os.path.join(static_dir, 'index.html')
        headers.append(('content-type', 'text/html;charset=utf-8'))
    else:
        res_path = os.path.join(static_dir, path[1:])
    if res_path.endswith('.html'):
        headers.append(('content-type', 'text/html;charset=utf-8'))
    elif any((res_path.endswith('.jpg'),
              res_path.endswith('.gif'),
              res_path.endswith('.png'))):
        headers.append(('content-type', 'text/html;charset=utf-8'))
    else:
        headers.append(('content-type', 'text/*;charset=utf-8'))
    # 生成响应头信息
    # make_resopnse('200 OK', [('content-type', 'image/*')])
    # for key, value in env.items():
    #     print(key, "  :  ", value)
    #     必须返回列表
    # return ['<h3>HI WSGI</h3>'.encode('utf-8')]
    #     判断资源是否存在
    status_code = 200
    if not os.path.exists(res_path):
        status_code = 404
        body.append('<h4 style = "color:red">不存在</h4>'.encode('utf-8'))
    else:
        with open(res_path, 'rb') as f:
            body.append(f.read())
    make_resopnse('%s OK' % status_code, headers)
    return body


# 生成web服务进程
httpd = make_server('localhost', 8111, app)
# 启动服务
httpd.serve_forever()
